import { MongoClient, Collection, WithId } from 'mongodb'

import config from './config'
import { IUser, IBooks, Token, Connect, Dingdan, Remark, Advices } from './types'

const client = new MongoClient(`mongodb://${config.mongo_host}`)

export let userCollection: Collection<WithId<IUser>>
export let booksCollection: Collection<WithId<IBooks>>
export let dingdansCollection: Collection<WithId<Dingdan>>
export let remarksCollection: Collection<WithId<Remark>>
export let connectCollection: Collection<WithId<Connect>>
export let advicesCollection: Collection<WithId<Advices>>
export let tokenCollection: Collection<WithId<Token>>

export async function toConnect() {
  await client.connect()
  console.log('Connected successfully to server')
  const db = client.db(config.mongo_db)
  userCollection = db.collection('user')
  booksCollection = db.collection('books')
  dingdansCollection = db.collection('dingdans')
  remarksCollection = db.collection('remarks')
  connectCollection = db.collection('connect')
  advicesCollection = db.collection('adivces')
  tokenCollection = db.collection('token')
  // 创建TTL索引
  tokenCollection.createIndex(
    {
      createdAt: 1
    },
    {
      expireAfterSeconds: 24 * 3600
    }
  )
}
